package com.jt.proxy;


import javafx.beans.property.ObjectProperty;

import java.lang.annotation.Target;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


public class JDKProxy {
    public static Object getProxy(Object target) {
        // 1.获取 类加载器
        ClassLoader loader = target.getClass().getClassLoader();
        // 2.获取接口数组类型
        Class<?>[] interfaces = target.getClass().getInterfaces();
        // 3.代理对象执行方法时的回调方法
        return Proxy.newProxyInstance(loader, interfaces, invocationHandler(target));
    }

    public static Object getTimeProxy(Object target) {
        ClassLoader classLoader = target.getClass().getClassLoader();
        Class<?>[] interfaces = target.getClass().getInterfaces();
        return Proxy.newProxyInstance(classLoader, interfaces, invocationHandler1(target));
    }

    public static InvocationHandler invocationHandler1(Object target) {
        return new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                long startTime = System.currentTimeMillis();
                Object invoke = method.invoke(target, args);
                long endTime = System.currentTimeMillis();

                System.out.println("耗时：" + (endTime - startTime));
                return invoke;
            }
        };
    }

    public static InvocationHandler invocationHandler(Object target) {
        return new InvocationHandler() {
            /**
             *
             * @param proxy
             * @param method
             * @param args
             * @return
             * @throws Throwable
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("事物开启");

                Object invoke = method.invoke(target, args);
                System.out.println("事物提交");
                return invoke;
            }
        };
    }
    public static Object getPoxy1(Object target){
        ClassLoader classLoader = target.getClass().getClassLoader();
        Class<?>[] interfaces = target.getClass().getInterfaces();
        return Proxy.newProxyInstance(classLoader, interfaces, invocationHandler2(target));
    }
    public static InvocationHandler invocationHandler2 (Object target){
        return new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return method.invoke(target, args);
            }
        };
    }
}
